import {
	type INodeType,
	type INodeTypeDescription,
	type IWebhookFunctions,
	type IWebhookResponseData,
} from 'n8n-workflow';
import { checkJWTToken, getCacheTask } from './util';

export class CallNode implements INodeType {
	description: INodeTypeDescription = {
		displayName: 'UNC任务回调',
		name: 'uncTaskCallbackTrigger',
		icon: 'file:webhook.svg',
		group: ['trigger'],
		version: 1,
		description: 'UNC任务回调',
		defaults: {
			name: 'UNC Task Callback Trigger',
		},
		credentials: [
			{
				name: 'JWTNodeApi',
				required: true,
				displayName: 'JWT凭证',
			},
		],
		webhooks: [
			{
				name: 'default',
				httpMethod: 'POST',
				responseMode: 'onReceived',
				path: '/taskcallback',
				isFullPath: true,
			},
		],
		inputs: [],
		outputs: ['main'],
		properties: [
		],
	};

	async webhook(this: IWebhookFunctions): Promise<IWebhookResponseData> {
		const resp = this.getResponseObject();
		try {
			const credentials: any = await this.getCredentials('JWTNodeApi');
			const headers = this.getHeaderData();
			checkJWTToken({
				secretKey: credentials?.keypass,
				token: headers?.authorization,
			});
		} catch (error) {
			// 必须成对出现
			resp.writeHead(403, { 'WWW-Authenticate': 'Basic realm="Webhook"' });
			resp.end(error?.message);
			return { noWebhookResponse: true };
		}
		// 需要触发创建异步任务的promise
		const params: any = this.getQueryData();
		const task_id = params?.id + '';
		const task_status = params?.status + '';
		const task = getCacheTask(task_id);
		if (task) {
			const body = this.getBodyData();
			if (task_status === 'error') {
				// 通知任务执行失败
				task?.reject(new Error('task execute error: ' + JSON.stringify(body)));
			} else {
				// 通知任务执行完成
				task?.resolve(body);
			}
		}
		return {
			webhookResponse: "OK",
		};
	}

}
